package com.yoomiito.app.ui.anyview.gasstation

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import cn.droidlover.xdroidmvp.cache.SharedPref
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.isNull
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import java.util.ArrayList

class SearchHistoryView (val context: Context){
    private var searchList: MutableList<String>?=null
    private var key:String = ""
    var onTagClickListener:(String)->Unit={}
    var tagFlowLayout:TagFlowLayout
    val view = LayoutInflater.from(context).inflate(R.layout.view_search_history,null,false).also {view->
        view.findViewById<ImageView>(R.id.del).setOnClickListener {
            searchList?.clear()
            SharedPref.getInstance(App.getInstance()).remove(key)
            setData(searchList!!)
            view.visibility = View.GONE
        }
        tagFlowLayout = view.findViewById<TagFlowLayout>(R.id.flowLayout).also{layout->
            layout.setOnTagClickListener { view, position, parent ->
                onTagClickListener(searchList?.get(position)!!)
                false
            }
        }
    }


    /**
     * 缓存关键字--key
     */
    fun init(key:String){
        this.key = key
        if (searchList.isNullOrEmpty()) {
            searchList = SharedPref.getInstance(App.getInstance()).getListData(key, String::class.java)
        }
        if (searchList.isNullOrEmpty())searchList= arrayListOf()
        setData(searchList!!)
    }

    private fun setData(data:List<String>){
        tagFlowLayout.adapter = object : TagAdapter<String>(data){
            override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                val tv = LayoutInflater.from(context).inflate(R.layout.item_tv, parent, false) as TextView
                tv.text = t
                return tv
            }

        }
    }

    fun saveHistory(keyword:String){
        if (!searchList?.contains(keyword)!!) {
            if (searchList?.size!! >= 5) {
                searchList?.removeAt((searchList?.size!!-1))
            }
            searchList?.add(0, keyword)
            SharedPref.getInstance(App.getInstance()).putListData(key, searchList)
        }
    }

    fun show(show:Boolean){
        init(key)
        view.visibility = if (show) if (searchList.isNullOrEmpty()) View.GONE else View.VISIBLE else View.GONE
    }
}